package com.yfbao.horizon.common;

import org.nustaq.serialization.FSTConfiguration;

import java.io.*;

public class LocalSerializationUtils {

    public LocalSerializationUtils() {
    }

    static FSTConfiguration configuration = FSTConfiguration
            // .createDefaultConfiguration();
            .createStructConfiguration();

    public static byte[] serialize(Object obj) {
        return configuration.asByteArray(obj);
    }

    public static Object unserialize(byte[] sec) {
        return configuration.asObject(sec);
    }
    public static Object unserializeAndClear(byte[] sec) {
        Object obj = configuration.asObject(sec);
        configuration.clearCaches();
//        try {
//            configuration.getObjectInput().close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return obj;
    }
//
//    public static byte[] kryoSerizlize(Object obj) {
//        Kryo kryo = new Kryo();
//        byte[] buffer = new byte[2048];
//        try(
//                Output output = new Output(buffer);
//        ) {
//
//            kryo.writeClassAndObject(output, obj);
//            return output.toBytes();
//        } catch (Exception e) {
//        }
//        return buffer;
//    }
//
//    static Kryo kryo = new Kryo();
//    public static Object kryoUnSerizlize(byte[] src) {
//        try(
//                Input input = new Input(src);
//        ){
//            return kryo.readClassAndObject(input);
//        }catch (Exception e) {
//        }
//        return kryo;
//    }

    // jdk原生序列换方案
    public static byte[] jdkserialize(Object obj) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos);) {
            oos.writeObject(obj);
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object jdkdeserialize(byte[] bits) {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bits);
             ObjectInputStream ois = new ObjectInputStream(bais)) {
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
